<template>
  <van-sticky>
    <div class="menu_header" style="height: 140rpx;"  >
     <van-cell  is-link 
	
	   :title="getSelectedShopName" 
	   style="height: 140rpx;"
	   @click="showPopup"
	   :label="getSelectedShopAddress"
	  />
	
 
    </div>
	 <van-popup
	      v-model:show="showBottom"
	      round
	      position="bottom"
	      :style="{ height: '30%' }"      style="z-index: 10000;"
	    >
	      <!-- 弹出层内容 -->
	      <div class="popup-content">
	        <van-cell
	          v-for="(shop, index) in shopList"
	          :key="index"
	          center
	          :title="shop.shopName"
	          :label="shop.shopAddress"
	          :value="`营业时间是 ${shop.startTime} ~ ${shop.endTime}`"
	          @click="selectShop(shop)"
			  style="margin-top: 20rpx;"
	        />
	      </div>
	    </van-popup>
  </van-sticky>
  <div class="menu_detail">
    <div class="menu_list">
      <van-sidebar v-model="tabValue">
        <van-sidebar-item
          :title="item.name"
          v-for="(item, index) in data.goods"
          :key="index"
          @click="handleMenulist(index)"
    	  
        />
      </van-sidebar>
    </div>
    <div id="goodListId" >
      <div v-for="(item1, index1) in data.goods" :key="index1" :id="'scroll' + index1">
        <div class="coffee_card">
          <span style="  margin: 20rpx;font-size: 32rpx; font-weight: bold; color: #676767;">{{ item1.name }}</span>
          <van-card
            v-for="(food, index2) in item1.foods"
            :key="index2"
            :price="food.price"
            :desc="food.description"
            :title="food.name"
            :thumb="food.image || defaultImage"
          >
            <template #footer>
              <van-stepper
                :show-minus="food.isStepperVisible"
                :show-input="food.isStepperVisible"
                v-model="food.num"
                theme="round"
                button-size="22"
                disable-input
                min="0"
                @change="updateCartItemQuantity(food, index1, index2)"
              />
            </template>
          </van-card>
        </div>
      </div>
    </div>
  </div>
  <view class="good-box" v-if="isMenuVisible && getCartGoodsPrice !== 0">
	       <div @tap="clearCart" class="clean">清空购物车</div>
		  <div class="menugoods" >
			   <li class="menugoodslist" v-for="food in getCartGoodsDetails" :key="food.name">
			             <span style="padding: 20rpx;">{{ food.name }}: 总价: {{ food.totalPrice }} 元</span>
			             <van-stepper
			               :show-minus="true"
			               :show-input="true"
			               v-model="food.num"
			               theme="round"
			               button-size="22"
			               disable-input
			               min="0"
			              @change="updateCartItemQuantity(food, food.index1, food.index2)"
			             />
			           </li>
		  </div>
  </view>
  <view class="cart-box" v-if="getCartGoodsPrice !== 0">
  	<view class="mark" >
  		<image src="/static/a1.png" class="cart-img" @tap="toggleMenu"></image>
  		
		<van-tag round type="primary" class="tag" style="margin-top: 30rpx;margin-left: 100rpx" >{{ getCartGoodsNumber }}</van-tag>
  	</view>
  	<view class="price">￥{{ getCartGoodsPrice }}</view>
	
  	<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">
  		{{ disabledPay ? `差${spread}元起送` : '去结算' }}
  	</button>
  </view>

  
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted, watchEffect,toRefs,computed } from 'vue';
import { listDish, listCategory,listShop } from '@/api/store/food.js';


import { useRouter } from 'vue-router';

// 获取 Vue Router 实例
const router = useRouter();


// 定义 toPay 方法
const toPay = () => {
	const cartItems = JSON.stringify(getCartGoodsDetails.value);
	uni.setStorageSync('cartItems', cartItems); // 存储数据
  
  uni.navigateTo({
    url: '../food/pay',
    success: function (res) {
      console.log('成功跳转到新页面');
    },
    fail: function (err) {
      console.error('跳转失败:', err);
    }
  });
};

// 定义默认图片
const defaultImage = 'https://example.com/default-image.jpg';
const selectedShop = ref(null);
const showBottom = ref(false);
const getSelectedShopName = computed(() => {
  return selectedShop.value ? selectedShop.value.shopName : shopList.value[0]?.shopName || '未选择店铺';
});
const getSelectedShopAddress = computed(() => {
  return selectedShop.value ? selectedShop.value.shopAddress : shopList.value[0]?.shopAddress || '未选择店铺';
});

// 显示弹出层的方法
const showPopup = () => {
  showBottom.value = true; // 点击时显示弹出层
};

// 选择店铺的方法
const selectShop = (shop) => {
  selectedShop.value = shop; // 更新选中的店铺
  showBottom.value = false; // 关闭弹出层
};

// 切换步进器显示状态的方法
const toggleStepper = (food) => {
  
  if (food.num === 0) {
    food.isStepperVisible = false;
  } else {
    food.isStepperVisible = true;
  }
};


// 获取购物车商品总数
const getCartGoodsNumber = computed(() => {
  return data.goods.reduce((acc, item) => {
    return acc + item.foods.reduce((sum, food) => sum + food.num, 0);
  }, 0);
});

// 获取购物车商品总价
const getCartGoodsPrice = computed(() => {
  return data.goods.reduce((acc, item) => {
    return acc + item.foods.reduce((sum, food) => sum + food.price * food.num, 0);
  }, 0);
});

   // 获取购物车中的商品名称和对应的总价及数量
    const getCartGoodsDetails = computed(() => {
      return data.goods.flatMap((item, index1) => 
        item.foods.filter(food => food.num > 0).map(food => ({
          ...food,
          totalPrice: food.price * food.num,
          index1,
          index2: item.foods.indexOf(food),
        }))
      );
    });

    // 设置商品数量
    const updateCartItemQuantity = (food, index1, index2) => {
      const item = data.goods[index1];
      const updatedFood = item.foods[index2];
      updatedFood.num = food.num;
	   toggleStepper(updatedFood);
	    localStorage.setItem(`food_num_${food.name}`, food.num);
    };

const toggleMenu = () => {
  isMenuVisible.value = !isMenuVisible.value;
};
const disabledPay =ref(false)
const isMenuVisible =ref(false)
const isStepperVisible =ref(true)
const value=ref(0)
const foodsUl = ref(null);
const scrollY = ref(0);
const tops = ref([]);
const menuWrapperRef = ref(null);
const foodsWrapperRef = ref(null);
const dishList = ref([]);
const categoryList = ref([]);
const shopList = ref([]);
const tabValue = ref(0);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
	
  },
  scrollY: 0, // 右侧滑动的Y轴坐标 (滑动过程时实时变化)
  tops: [], // 所有右侧分类li的top组成的数组  (列表第一次显示后就不再变化)
  goods: [], // 最终的分组数据
});

const { queryParams, form, rules } = toRefs(data);




function clearCart() {
  data.goods.forEach(item => {
    item.foods.forEach(food => {
      food.num = 0;
      food.totalPrice = 0;
    });
  });
  isMenuVisible.value = !isMenuVisible.value;
}

function getList() {
  
  listShop(queryParams.value).then(response => {
    shopList.value = response.rows;
	console.log(shopList.value[0].shopName)
	console.log(shopList)
  });
  
 
  
}

function takein() {
	
  	
  listDish(queryParams.value).then(response => {
    dishList.value = response.rows;
    console.log(dishList.value)
    console.log(dishList)
    // 分组并转换数据格式
    const groupedData = groupAndTransformDishes(dishList.value);
    data.goods = groupedData;
	groupedData.forEach(item => {
	      item.foods.forEach(food => {
	        food.num = 0; // 初始化 num 为 0
			food.isStepperVisible = false;
	      });
		  
	    });
   
    
	
	//缓存数据
	groupedData.forEach((category) => {
	  category.foods.forEach((food) => {
	    const savedNum = localStorage.getItem(`food_num_${food.name}`);
	    if (savedNum !== null) {
	          food.num = parseInt(savedNum, 10);
	    
				  // 根据 num 的值设置 isStepperVisible
	          food.isStepperVisible = food.num !== 0;
	        } else {
	          // 如果没有缓存 num 的值，默认设置 num 和 isStepperVisible
	          food.num = 0;
	          food.isStepperVisible = false; // 默认设置为 true
	        }
	    
	        // 将 isStepperVisible 的值缓存到 localStorage
	        localStorage.setItem(`food_isStepperVisible_${food.name}`, food.isStepperVisible);
		
		
	  });
	});
		   
  });
  
  

  listCategory(queryParams.value).then(response => {
    categoryList.value = response.rows;
  });
  
}

// 分组并转换数据格式
function groupAndTransformDishes(dishes) {
  return dishes.reduce((acc, dish) => {
    const categoryName = dish.categoryName || '未知分类';
    const categoryIndex = acc.findIndex(item => item.name === categoryName);

    if (categoryIndex === -1) {
      acc.push({
        icon: "http://liangziqi.top/meme-img/126-430.jpg", // 默认图标
        name: categoryName,
        foods: [dish]
      });
    } else {
      acc[categoryIndex].foods.push(dish);
    }

    return acc;
  }, []);
}

// 左侧菜单点击联动左侧
const handleMenulist = (index) => {
  tabValue.value = index;
  const navPage = document.querySelector(`#scroll${index}`);
  if (navPage) {
    const goodListId = document.querySelector('#goodListId');
    if (goodListId) {
      goodListId.scrollTop = navPage.offsetTop - 165;
    }
  }
}

// 右侧菜单联动左侧
const handleScroll = () => {
  const goodListId = document.querySelector('#goodListId');
  if (!goodListId) {
    return;
  }

  const scrollTop = goodListId.scrollTop;
  for (let a = 0; a < data.goods.length; a++) {
    const navPage = document.querySelector(`#scroll${a}`);
    if (navPage && navPage.offsetTop - 170 < scrollTop) {
      tabValue.value = a;
    }
  }
}

defineExpose({
  tabValue,
  handleMenulist
});

onMounted(() => {
  getList();	
  takein();
  window.addEventListener('scroll', handleScroll, true);

  // 清理事件监听
  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
});

watchEffect(() => {});

</script>



<style>
	.clean{
		float: right;margin-right: 40rpx;
		margin-top: 20rpx;
		color:#FF6900;
	}
    .menu_detail{
        height: calc(100vh - 140px);
        display:flex;
    }

    .menu_list{
        width:auto;
        height: 100%;
        background-color: #FDF1EA;
    }

    #goodListId{
        overflow: auto;
        width: -webkit-fill-available;
		
    }

    /* 选中标签三角标识 */
    .van-sidebar-item--select:before {
        position: absolute;
        top: 50%;
        left: 0;
        width: 0;
        height: 0;
        border-top: 5px solid transparent;
        border-left: 10px solid #FF6900;
        border-bottom: 5px solid transparent;
        -webkit-transform: translateY(-50%);
        background-color:#fff;
        transform: translateY(-50%);
        content: '';
    }
	
	.good-box{
		position: absolute;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		
		border-radius: 48rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
		background-color: #ffffff;
		  display: block;
		  max-height: 300px; /* 根据实际需求调整高度 */
		  overflow-y: auto;  /* 允许垂直滚动 */
		align-items: center;
		justify-content: space-between;
		z-index: 9999;
		margin-bottom: 20rpx;
	
	}
	.menugoods {
		padding: 30rpx;
	    margin: 20rpx;
		background-color: #fff;
		
		flex-direction:row;
		margin-bottom: 150rpx;
		margin-top: 40rpx;
		 
	}
	.menugoodslist{
		display: flex;
		  align-items: center;
		  padding: 10px;
		  border-bottom: 1px solid #e0e0e0;
		  font-size: 16px;
		  color: #555;
	}
	
	.cart-box {
		position: absolute;
		bottom: 30rpx;
		left: 30rpx;
		right: 30rpx;
		height: 96rpx;
		border-radius: 48rpx;
		box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 9999;
		}
		
		
		.pay-btn {
			height: 100%;
			padding: 0 30rpx;
			color: #FFFFFF;
			border-radius: 0 50rpx 50rpx 0;
			display: flex;
			align-items: center;
		
		}
		.cart-img {
			width: 303rpx;
			height: 202rpx;
			position: relative;
			margin-top: -96rpx;
			margin-left: -20rpx;;
		}
		
		
		.mark {
			padding-left: 46rpx;
			margin-right: 30rpx;
			position: relative;
			
			
		}
		.tag {
		
			display: flex;
			justify-content: center;
			align-items: center;
			
			position: absolute;
			right: -10rpx;
			top: -50rpx;
			border-radius: 100%;
			padding: 4rpx;
			width: 40rpx;
			height: 40rpx;
			opacity: .9;
		}
		.price {
			flex: 1;
			
		}
	    .notice-swipe {
	        height: 40px;
	        line-height: 40px;
	      }
	
</style>

